package cn.monkey.data.mongo;

import cn.monkey.data.entity.dto.TenantQueryRequest;
import cn.monkey.data.mongo.ds.MongoBeforeSelectBehavior;
import cn.monkey.data.repository.BeforeCreateBehavior;
import cn.monkey.data.repository.BeforeSelectBehavior;
import cn.monkey.data.repository.BeforeUpdateBehavior;
import cn.monkey.data.repository.RepositoryBehaviorContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.Optional;

public class MongoRepositoryBehaviorContext<T> implements RepositoryBehaviorContext<TenantQueryRequest, Criteria, T>, ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private BeforeSelectBehavior<TenantQueryRequest, Criteria> beforeSelectBehavior;

    private BeforeCreateBehavior<T> beforeCreateBehavior;

    private BeforeUpdateBehavior<T> beforeUpdateBehavior;

    @Override

    public Optional<BeforeSelectBehavior<TenantQueryRequest, Criteria>> beforeSelectBehavior() {
        return Optional.ofNullable(this.beforeSelectBehavior);
    }

    @Override
    public Optional<BeforeCreateBehavior<T>> beforeCreateBehavior() {
        return Optional.ofNullable(this.beforeCreateBehavior);
    }

    @Override
    public Optional<BeforeUpdateBehavior<T>> beforeUpdateBehavior() {
        return Optional.ofNullable(this.beforeUpdateBehavior);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void afterPropertiesSet() throws Exception {
        try {
            this.beforeSelectBehavior = this.applicationContext.getBean(MongoBeforeSelectBehavior.class);
        } catch (Exception ignore) {
        }
        try {
            this.beforeCreateBehavior = this.applicationContext.getBean(BeforeCreateBehavior.class);
        } catch (Exception ignore) {
        }
        try {
            this.beforeUpdateBehavior = this.applicationContext.getBean(BeforeUpdateBehavior.class);
        } catch (Exception ignore) {
        }
    }
}
